package com.cmol.peopledetectapp.user;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.cmol.data.GlobalData;
import com.cmol.data.Host;
import com.cmol.data.SettingData;
import com.cmol.net.Network;
import com.cmol.peopledetectapp.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Proxy;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 用户意见反馈
 *
 * @author 张瀚文
 */
public class SuggestionActivity extends AppCompatActivity {
    /**
     * 用户输入的建议
     */
    private EditText suggestion;
    /**
     * 布局
     */
    private TextView textView;
    private Button button;
    /**
     * 通信模块
     */
    private Network network;
    /**
     * 反馈发送状态
     */
    private String isSuccess = new String();
    /**
     * 布局文件
     */
    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suggest);

        suggestion = findViewById(R.id.suggestion);
        button = findViewById(R.id.btn);
        textView = findViewById(R.id.SuggestTitleText);
        view = findViewById(R.id.SuggestionBackground);
//        button.setOnClickListener(Submit1(view));

        SystemSetting();
    }

    /**
     * 提交建议
     *
     * @param view 布局文件
     */
    public void Submit1(View view) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("note", suggestion.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, "" + jsonObject.toString());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .build();
        Request request = new Request.Builder()
                .url(Host.host + "/user/sendFeedBack")
                .addHeader("Authorization", GlobalData.getUserToken())
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        /**
         * 异步响应
         */
        call.enqueue(new Callback() {
            /**
             * Called when the request could not be executed due to cancellation, a connectivity problem or
             * timeout. Because networks can fail during an exchange, it is possible that the remote server
             * accepted the request before the failure.
             *
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("==============body:", e.toString());
                        Toast.makeText(SuggestionActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            /**
             * Called when the HTTP response was successfully returned by the remote server. The callback may
             * proceed to read the response body with . The response is still live until
             * its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
             * consume the response body on another thread.
             *
             * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
             * not necessarily indicate application-layer success: {@code response} may still indicate an
             * unhappy HTTP response code like 404 or 500.
             *
             * @param call
             * @param response
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = Objects.requireNonNull(response.body()).string().trim();
//                Log.e("=====================res",response.toString());
                Log.e("====body: ", res);
                if (response.code() == 200) {
                    try {
                        JSONObject json = new JSONObject(res);
                        /**
                         * token:
                         * boolean auth:
                         */
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SuggestionActivity.this, "服务器异常" + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });

        AlertDialog textTips = new AlertDialog.Builder(SuggestionActivity.this).setMessage("提交成功!").create();
        textTips.show();

    }

    /**
     * 提交
     *
     * @param view 布局文件
     */
    private void Submit(View view) {
        JSONObject tmp = new JSONObject();
        try {
            tmp.put("note", suggestion.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        network = new Network(tmp, "/user/sendFeedBack") {
            @Override
            protected void process(Call call, Response response) throws IOException {
                String ans = Objects.requireNonNull(response.body()).string().trim();
                try {
                    JSONObject js = new JSONObject(ans);
                    // 接收服务器反馈的成功信息
                    isSuccess = js.getString("sendFeedBack");
                    Log.e("result:====================", isSuccess);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void failureWarn() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SuggestionActivity.this, "建议提交失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };

        /**
         * 根据语言提示成功
         */
        if (SettingData.getLANGUAGE() == false) {
            AlertDialog textTips = new AlertDialog.Builder(SuggestionActivity.this).setMessage(isSuccess).create();
            textTips.show();
        } else {
            AlertDialog textTips = new AlertDialog.Builder(SuggestionActivity.this).setMessage("提交成功!").create();
            textTips.show();
        }
    }

    /**
     * 系统设置
     */
    private void SystemSetting() {
        if (SettingData.getCOLOR() == false) {
            view.setBackgroundResource(R.drawable.redbackground);
            button.setBackgroundResource(R.drawable.button_red);
            suggestion.setBackgroundResource(R.drawable.background_orangeeditext);
        } else {
            view.setBackgroundResource(R.drawable.background_iner);
            button.setBackgroundResource(R.drawable.button_blue);
            suggestion.setBackgroundResource(R.drawable.background_editext);
        }

        if (SettingData.getLANGUAGE() == false) {
            suggestion.setHint("Please Input Your Advice");
            button.setText("Submit");
            textView.setText("Suggestion Feedback");
        } else {
            suggestion.setHint("请输入建议或意见");
            button.setText("提交");
            textView.setText("意见反馈");
        }
    }
}